﻿
// HttpPostTestDlg.cpp: 实现文件
//

#include "pch.h"
#include "until.h"
#include "framework.h"
#include "HttpPostTest.h"
#include "HttpPostTestDlg.h"
#include "afxdialogex.h"
//rapidjson的头文件
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <rapidjson/reader.h>
#include <curl.h>
#include  <string>
#include<iostream> 
#include<stdio.h>

#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"


using namespace rapidjson;

using namespace   std;

#ifdef _DEBUG
#define new DEBUG_NEW
#endif





size_t WritePostBodyResp(void* buffer, size_t size, size_t nmemb, void* userp)
{
	static_cast<string*>(userp)->append(static_cast<char*>(buffer), 0, size * nmemb);
	return size * nmemb;
};

size_t WritePostHeaderResp(void* buffer, size_t size, size_t nmemb, void* userp)
{
	static_cast<string*>(userp)->append(static_cast<char*>(buffer), 0, size * nmemb);
	return size * nmemb;
};

//创建dhl的发送内容
std::string  CreatePostFiled(char* str_cmp_ID, char* str_hawb)
{
	//字符串缓冲区
	rapidjson::StringBuffer  m_strBuffer;
	//建立写对象
	rapidjson::Writer<rapidjson::StringBuffer>  m_Writer(m_strBuffer);
	//[]:StartArray()/EndArray() :数组       {}：StartObject/EndObject:对象
	m_Writer.StartArray();
	m_Writer.StartObject();
	//机构代码
	m_Writer.Key("declGTW");
	m_Writer.String(str_cmp_ID);
	//单号
	m_Writer.Key("hawb");
	m_Writer.String(str_hawb);

	m_Writer.EndObject();
	m_Writer.EndArray();

	return  std::string(m_strBuffer.GetString());
}

int http_nah_dhl_post(CURL* p_curl, char* url, char* body, char* strOutHead /*= NULL*/, char* strOutBody /*= NULL*/)
{
	int m_nResult = 0;
	struct curl_slist* headers = NULL;
	std::string respBodyData;
	std::string respHeadData;
	CURL* curl = p_curl;
	CURLcode res;


	if (curl == nullptr)
	{
		LOG(INFO) << "Create curl handle failed";
		return -1;
	}

	headers = curl_slist_append(headers, "Content-Type:text/xml");
	headers = curl_slist_append(headers, "Accept:text/xml");
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);//设置HTTP头
	
	curl_easy_setopt(curl, CURLOPT_URL, url);
	LOG(INFO) << url;
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "");
	curl_easy_setopt(curl, CURLOPT_POST, 1);

	curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, WritePostHeaderResp);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WritePostBodyResp);
	curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &respHeadData);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &respBodyData);

	bool bCA = FALSE;
	if (!bCA)
	{
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE);//设定为不验证证书和HOST 
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	}
	else
	{
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, TRUE);
		curl_easy_setopt(curl, CURLOPT_CAINFO, "");
	}
    //执行获取指令
	res = curl_easy_perform(curl);
	if (res != CURLE_OK)
	{
		LOG(INFO) << curl_easy_strerror(res);
		m_nResult = -1;
	}
	//utf-8转 char
	if (m_nResult >= 0)
	{
		if (strOutHead)
		{
			strcpy(strOutHead, Utf8ToAscii(respHeadData).c_str());
			
			LOG(INFO) << "----------------------------------RECV_HEAD------------------------------------------";
			LOG(INFO) << strOutHead;
		}
		if (strOutBody)
		{
			strcpy(strOutBody, Utf8ToAscii(UTF8Url::Decode(respBodyData)).c_str());
			
			LOG(INFO) << "----------------------------------RECV_BODY------------------------------------------";
			LOG(INFO) << strOutBody;
		}
	}
	return m_nResult;
}


// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CHttpPostTestDlg 对话框



CHttpPostTestDlg::CHttpPostTestDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_HTTPPOSTTEST_DIALOG, pParent)
	, m_str_nah_cur(_T(""))
	, m_str_result_text(_T(""))
	, m_str_bar_code(_T(""))
	, m_str_send_text(_T(""))
	, m_str_pvg_code(_T(""))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

CHttpPostTestDlg::~CHttpPostTestDlg()
{
	if (m_cSFBodyRespnse)
	{
		delete[] m_cSFBodyRespnse;
		m_cSFBodyRespnse = nullptr;
	}
	if (m_cSFHeadRespose)
	{
		delete[] m_cSFHeadRespose;
		m_cSFHeadRespose = nullptr;
	}
}

void CHttpPostTestDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT1, m_str_nah_cur);
	DDX_Control(pDX, IDC_EDIT2, m_str_result);
	DDX_Text(pDX, IDC_EDIT2, m_str_result_text);
	DDX_Text(pDX, IDC_EDIT3, m_str_bar_code);
	DDX_Text(pDX, IDC_EDIT4, m_str_send_text);
	DDX_Text(pDX, IDC_EDIT5, m_str_pvg_code);
}

BEGIN_MESSAGE_MAP(CHttpPostTestDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDOK, &CHttpPostTestDlg::OnBnClickedOk)
	ON_BN_CLICKED(IDOK2, &CHttpPostTestDlg::OnBnClickedOk2)
END_MESSAGE_MAP()


// CHttpPostTestDlg 消息处理程序

BOOL CHttpPostTestDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码
	 GetProgramFullPath();
	 InitLogSetting();
	
	curl_global_init(CURL_GLOBAL_ALL);
	
	m_cSFBodyRespnse = new char[1024 * 10];//10KB字节
	m_cSFHeadRespose = new char[1024 * 4];//头返回

	m_str_nah_cur = "http://23.156.60.119:8085/NAHCDMSIMP/QueryShipDetailServlet?EData=";
	m_str_pvg_code = "PVG";
	//m_str_bar_code = "[{'declGTW':'PVG','hawb':'8260838888'},{'declGTW':'PVG','hawb':'8270839294'}]";
	UpdateData(false);
	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CHttpPostTestDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CHttpPostTestDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CHttpPostTestDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



void CHttpPostTestDlg::OnBnClickedOk()
{
	UpdateData(true);
	std::string m_str_union_url;
	std::string strIntRequest="";
	std::string str_utf8_Requeset;
	CURL* m_curl_handle = curl_easy_init();
	if (m_curl_handle)
	{
		strIntRequest.clear();
		strIntRequest.clear();
		strIntRequest = CreatePostFiled(m_str_pvg_code.GetBuffer(0), static_cast<char*>(m_str_bar_code.GetBuffer(0)));//条码
		//strIntRequest = static_cast<char*>(m_str_bar_code.GetBuffer(0));
		str_utf8_Requeset= UTF8Url::Encode(AsciiToUtf8(strIntRequest));
		m_str_union_url = m_str_nah_cur.GetBuffer(0);
		m_str_union_url += str_utf8_Requeset;
		LOG(INFO) << m_str_union_url;
		//发送内容
		m_str_send_text = str_utf8_Requeset.c_str();
		UpdateData(false);
		//开始发送
		ZeroMemory(m_cSFHeadRespose, 1024 * 4);
		ZeroMemory(m_cSFBodyRespnse, 1024 * 10);
		if(http_nah_dhl_post(m_curl_handle, (char*)m_str_union_url.c_str(), (char*)str_utf8_Requeset.c_str(), m_cSFHeadRespose, m_cSFBodyRespnse)>=0)
		{
			if (true)
			{
				Document document;
				document.Parse(m_cSFBodyRespnse);
				const auto& array=document.GetArray();
				for (const auto& e : array)
				{
					const auto& m_str_description = e["localDescription"].GetString();
					m_str_result_text = m_str_description;
					UpdateData(false);
				}
			}
			//m_str_result_text = m_cSFBodyRespnse;
			
		}
		else
		{
			LOG(INFO) << "http_nah_dhl_post  failed";
		}
	}

	curl_easy_cleanup(m_curl_handle);
}


void CHttpPostTestDlg::OnBnClickedOk2()
{
	// TODO: 在此添加控件通知处理程序代码
}
